import { getServerSession } from 'next-auth/next';
import { authOptions } from './auth/[...nextauth]';
import fs from 'fs';
import path from 'path';

export default async function handler(req, res) {
  const session = await getServerSession(req, res, authOptions);

  if (req.method === 'GET') {
    try {
      const filePath = req.query.filePath || 'index.md';
      const fullPath = path.join(process.cwd(), filePath);
      
      // 检查文件是否存在
      if (!fs.existsSync(fullPath)) {
        return res.status(404).json({ error: '文件不存在' });
      }

      const content = fs.readFileSync(fullPath, 'utf8');
      res.status(200).json({ content });
    } catch (error) {
      console.error('Error reading file:', error);
      res.status(500).json({ error: '读取文件失败' });
    }
  } else if (req.method === 'POST') {
    if (!session?.user?.isAdmin) {
      return res.status(403).json({ error: '需要管理员权限' });
    }

    try {
      const { content } = req.body;
      const filePath = req.query.filePath || 'index.md';
      const fullPath = path.join(process.cwd(), filePath);

      if (!content) {
        return res.status(400).json({ error: '内容不能为空' });
      }

      fs.writeFileSync(fullPath, content, 'utf8');
      res.status(200).json({ message: '保存成功' });
    } catch (error) {
      console.error('Error saving file:', error);
      res.status(500).json({ error: '保存文件失败' });
    }
  } else {
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
} 